//
//  SinaOauthViewController.swift
//  SinaWeiBo
//
//  Created by 刘世瑛 on 16/1/21.
//  Copyright © 2016年 刘世瑛. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class SinaOauthViewController: UIViewController ,UIWebViewDelegate{

    
   
    let webView = UIWebView()
    override func loadView() {
        view = webView
        setUpNav()
        webView.delegate = self
        
    }
    

    override func viewDidLoad() {
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)")
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
    }
    
    private func setUpNav()
    {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "turnBack")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }
    
    @objc private func turnBack()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFill()
    {
        let js = "document.getElementById('userId').value=\"ruoruchujian641@sina.com\";document.getElementById('passwd').value=\"mobai641\""
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    
    private func loadInfor(code:String)
    {
    let afn = AFHTTPSessionManager()
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        let parameters = ["client_id":client_id , "client_secret":client_secret , "grant_type":"authorization_code" , "code":code , "redirect_uri":redirect_uri]
    afn.POST("https://api.weibo.com/oauth2/access_token", parameters: parameters, success: { (_, JSON) -> Void in
        let dic = JSON as! [String: AnyObject]
        let accountModel = SinaAccountModel(dic: dic)
        self.loadUserInfor(accountModel)
        
        }) { (_, error) -> Void in
            print(error)
        }
    }
    
    
    //通过token 获取用户参数
    private func loadUserInfor(accountMode:SinaAccountModel)
    {
        let afn = AFHTTPSessionManager()
        
        let url = "https://api.weibo.com/2/users/show.json"
        let para : [String :AnyObject] = ["access_token":accountMode.access_token!,"uid":accountMode.uid!]
        afn.GET(url, parameters: para, progress: nil, success: { (_, JSON) -> Void in
            
            print(JSON)
            if let dic = JSON as? [String : AnyObject]{
                accountMode.screen_name = dic["screen_name"] as? String
                accountMode.profile_image_url = dic["profile_image_url"] as? String
                accountMode.saveCoder()
        
            }
            }) { (_, error) -> Void in
                print(error)
        }
    }
   
    
    
    

    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    //发送请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if let url = request.URL?.absoluteString{
        if url.hasPrefix(redirect_uri){
            
            print(url)
            
            if  let code = request.URL?.query{
            let subStr = code.substringFromIndex("code=".endIndex)
                loadInfor(subStr)
            }
            
      
            return false
            
            }}
        return true
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
